<template>
  <div class="role-page">
    <div class="btns-fun-field">
      <el-button
        v-if="rolePermission.addRolePerm"
        type="primary"
        @click.prevent="showAddEditDialog"
        :icon="Plus"
      >
        新增角色
      </el-button>
    </div>
    <div class="table-field">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="id" label="id" width="120" />
        <el-table-column prop="name" label=" " width="160" />
        <el-table-column prop="createTime" label="创建时间" width="240" />
        <el-table-column label="操作" min-width="220px">
          <template #default="scope">
            <el-button
              v-if="rolePermission.editRolePerm"
              type="success"
              size="small"
              @click.prevent="showAddEditDialog(scope.row, 2)"
              >编辑</el-button
            >
            <el-button
              v-if="rolePermission.removeRolePerm"
              type="danger"
              size="small"
              @click.prevent="showRemoveDialog(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-field">
      <el-pagination
        v-model:current-page="formData.pageIndex"
        v-model:page-size="formData.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="formData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="角色名" prop="name">
            <el-input
              v-model="addEditForm.name"
              autocomplete="off"
              placeholder="请输入角色名"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="权限" prop="permissionIdList">
            <div
              style="
                max-height: 400px;
                min-height: 100px;
                width: 100%;
                overflow: auto;
              "
            >
              <el-tree
                node-key="id"
                :default-checked-keys="checkedKeys"
                default-expand-all
                :data="permissionList"
                :props="props"
                show-checkbox
                @check-change="treeSelect"
                check-strictly
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除角色"
      width="400px"
    >
      <span>确定要删除当前角色？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getRolePagination,
  addRole,
  updateRole,
  removeRole,
  getPermissionTree,
} from "@/api/userManage.api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, selectKey, FormInstance } from "element-plus";
import { useRolePermission } from "@/utils/permission.utils";
const rolePermission = useRolePermission();
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

const props = {
  label: "menuName",
  children: "children",
};

const removeDialogVisible = ref(false);
const addDialogVisible = ref(false);
const addEditRef = ref<FormInstance>();
const addEditForm = reactive({
  id: null,
  name: "",
  remark: "",
  disabled: false,
  title: "",
  permissionIdList: [],
});
const addEditRules = reactive({
  name: [
    { required: true, message: "请输入角色名", trigger: "blur" },
    { min: 1, max: 30, message: "长度为1~30位", trigger: "blur" },
  ],
});

const showAddEditDialog = (item: any, type: number) => {
  //新增角色
  if (item.target) {
    addEditForm.id = null;
    addEditForm.name = "";
    addEditForm.remark = "";
    addEditForm.disabled = false;
    addEditForm.title = "新增角色";
    addDialogVisible.value = true;
    checkedKeys.value = [];
    return;
  }

  addEditForm.id = item.id;
  addEditForm.name = item.name;
  addEditForm.remark = item.remark;
  checkedKeys.value = item.permissionIdList;
  //查看详情
  if (type === 1) {
    addEditForm.title = "查看详情";
    addEditForm.disabled = true;
    addDialogVisible.value = true;
    return;
  }

  //编辑
  addEditForm.title = "编辑角色";
  addEditForm.disabled = false;
  addDialogVisible.value = true;
};

const tableLoading = ref(false);
const tableData = ref([]);

const curSelectRow = ref("");
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startRemoveRole = () => {
  let id = curSelectRow.value?.id;
  removeRole([id])
    .then((res) => {
      console.log("success~~~~~");
      removeDialogVisible.value = false;
      ElMessage({
        message: "角色删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      removeDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
};

const startAddRole = () => {
  let formData = {
    name: addEditForm.name,
    remark: addEditForm.remark,
    permissionIdList: checkedKeys.value,
  };

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (addEditForm.id) {
        updateRole({
          ...formData,
          id: addEditForm.id,
        })
          .then((res) => {
            addDialogVisible.value = false;
            ElMessage({
              message: "角色修改成功",
              type: "success",
            });
            getDataList();
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: "error",
            });
          });
        return;
      }

      addRole(formData)
        .then((res) => {
          addDialogVisible.value = false;
          ElMessage({
            message: "角色新增成功",
            type: "success",
          });
          getDataList();
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};

const getDataList = () => {
  tableLoading.value = true;
  getRolePagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {
      tableLoading.value = false;
      console.log(".......................");
      console.log(res);
      console.log(".......................");
      tableData.value = res.list || [];
      formData.total = Number(res.total);
    })
    .catch((error) => {
      console.log(error);
      tableLoading.value = false;
    });
};

const permissionList = ref([]);
const flatPermissionList = ref([]);
const checkedKeys = ref<any>([]);

const treeSelect = (item: any, curStatus: boolean) => {
  //如果是选中，则查询其父节点是否选中，如果没有选中，则把父节点也选中。
  if (curStatus) {
    let checkKeyList = checkedKeys.value;
    let parentIdList = checkParentNode(item);
    checkedKeys.value = [
      ...new Set([item.id, ...parentIdList, ...checkKeyList]),
    ];
  } else {
    checkedKeys.value = checkedKeys.value.filter((row) => row != item.id);
  }
};

const checkParentNode = (item: any): Array<any> => {
  let list = [];
  let flatNodeList = flatPermissionList.value;
  let findRes = flatNodeList.find((row) => row.id == item.parentId);
  if (findRes) {
    list.push(findRes.id);
    if (findRes.parentId) {
      let subList = checkParentNode(findRes);
      list.push(...subList);
    }
  }
  return list;
};

const flatTree = (treeData: any) => {
  return treeData.reduce((first: any, last: any) => {
    first.push(last);
    if (last.children && last.children.length) {
      first.push(...flatTree(last.children));
    }
    return first;
  }, []);
};

const startGetPermissionTree = () => {
  getPermissionTree({}).then(function (res: any) {
    permissionList.value = res;
    flatPermissionList.value = flatTree(res);
    console.log("flatPermissionList ", flatPermissionList.value);
  });
};

onMounted(() => {
  getDataList();
  startGetPermissionTree();
});
</script>
<style lang="scss" scoped>
.role-page {
  background-color: #fff;
  padding: 20px;
  max-height: calc(100vh - 134px);
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}
</style>
